package com.yuchen.advsdk.manager;

import android.app.Application;
import android.content.ContentValues;
import android.content.Context;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSONArray;
import com.yuchen.advsdk.Constant;
import com.yuchen.advsdk.FileDownloader.OkDlListener;
import com.yuchen.advsdk.FileDownloader.OkDlManager;
import com.yuchen.advsdk.FileDownloader.OkDlTask;
import com.yuchen.advsdk.db.ConditionBuilder;
import com.yuchen.advsdk.db.DbUtil;
import com.yuchen.advsdk.eb.EbPreDownload;
import com.yuchen.advsdk.eb.EbVideoDownloadedCompleted;
import com.yuchen.advsdk.model.DbVideoFile;
import com.yuchen.advsdk.net.AJsonParser;
import com.yuchen.advsdk.net.API;
import com.yuchen.advsdk.net.NetWork;
import com.yuchen.advsdk.net.NetWorkStringCallBack;
import com.yuchen.advsdk.util.AsyncTaskUtil;
import com.yuchen.advsdk.util.DateTimeUtil;
import com.yuchen.advsdk.util.LogUtils;
import com.yuchen.advsdk.util.SPManager;
import com.yuchen.advsdk.util.SafeHandler;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.List;

public class VideoDownloadManager {
    private static final String TAG = "VideoDownloadManager";
    private static VideoDownloadManager instance;
    private boolean inited = false;
    private Context context;
    private static SafeHandler handler;

    public boolean isInited() {
        return inited;
    }

    public static synchronized VideoDownloadManager getInstance() {
        if (instance == null) {
            instance = new VideoDownloadManager();
        }
        return instance;
    }

    public void addDownload(final String url, final String md5) {
        LogUtils.d(TAG,"addDownload : "+url+" > "+md5);
        AsyncTaskUtil.run(new AsyncTaskUtil.Task2() {
            @Override
            public void taskRun() {
                synchronized (VideoDownloadManager.class) {
                    DbVideoFile df = DbUtil.findFirst(DbVideoFile.class, ConditionBuilder.getInstance().start().addCondition("md5", md5).end());
                    if (df == null) {
                        df = new DbVideoFile(url, md5, System.currentTimeMillis());
                        DbUtil.save(df);
                        OkDlManager.getInstance().addTask(1, url, Constant.path_download_video);
                    }else{
                        LogUtils.d(TAG,"addDownload task is not null");
                    }
                }
            }
        });

    }

    public synchronized void init(Context context) {
        this.context = context;
        OkDlManager.init((Application) context.getApplicationContext());
//        Looper.prepare();//增加部分
//        handler = new SafeHandler();
//        Looper.loop();
        File file = new File(Constant.path_download_video);
        if (!file.exists()){
            file.mkdirs();
        }
        inited = true;
        OkDlManager.getInstance().addDlListener(1, new OkDlListener() {
            @Override
            public void onPrepare(OkDlTask task) {
                ContentValues values = new ContentValues();
                values.put("path", task.getLocalPath());
                DbUtil.update(DbVideoFile.class, values, ConditionBuilder.getInstance().start().addCondition("url", task.getUrl()).end());

            }

            @Override
            public void onStart(OkDlTask task) {

            }

            @Override
            public void onProgress(OkDlTask okDlTask) {
                LogUtils.d(TAG,okDlTask.getFileName() + " - " + okDlTask.getTotalLength() + " - " + okDlTask.getCurrentLength());
            }

            @Override
            public void onStop(OkDlTask task) {

            }

            @Override
            public void onError(OkDlTask task, String error) {
                LogUtils.d(TAG,"下载异常："+task.toString());

                DbVideoFile dfTask = DbUtil.findFirst(DbVideoFile.class, ConditionBuilder.getInstance().start().addCondition("url", task.getUrl()).end());
                if (dfTask!=null && dfTask.getRetryCount()>=3){
                    DbUtil.delete(DbVideoFile.class,  ConditionBuilder.getInstance().start().addCondition("url", dfTask.getUrl()).end());
//                    DbUtil.delete(OkDlTask.class, ConditionBuilder.getInstance().start().addCondition("url", dfTask.getUrl()).end());
//                    File f = new File(task.getLocalPath());
                    OkDlManager.getInstance().cancleTask(task.getUrl());
                }else{
                    ContentValues values = new ContentValues();
//                    values.put("status", OkDlTask.Status.STATUS_PAUSE);
                    values.put("retryCount",dfTask.getRetryCount()+1);
                    DbUtil.update(DbVideoFile.class, values, ConditionBuilder.getInstance().start().addCondition("url", task.getUrl()).end());
                    OkDlManager.getInstance().resumeTask(task.getUrl());
                }

            }

            @Override
            public void onFinish(OkDlTask task) {
                LogUtils.d(TAG,"下载成功："+task.toString());
                ContentValues values = new ContentValues();
                values.put("status", DbVideoFile.Status.STATUS_SUCCESS);
                DbUtil.update(DbVideoFile.class, values, ConditionBuilder.getInstance().start().addCondition("url", task.getUrl()).end());
                DbVideoFile df  = DbUtil.findFirst(DbVideoFile.class, ConditionBuilder.getInstance().start().addCondition("url", task.getUrl()).end());
                if (null !=df){
                    EventBus.getDefault().post(new EbVideoDownloadedCompleted(task.getLocalPath(),df.getMd5()));
                }

            }

            @Override
            public void onCancle(OkDlTask task) {

            }
        });


    }

    public void resumeAllTask(){
        OkDlManager.getInstance().resumeAllTask();
    }


    public void checkFile(){
       LogUtils.d(TAG,"checkFile");
        List<DbVideoFile> list = DbUtil.find(DbVideoFile.class, ConditionBuilder.getInstance().start().addCondition("status", OkDlTask.Status.STATUS_SUCCESS).end());
        for (DbVideoFile df : list){
            if (TextUtils.isEmpty(df.getPath())){
                DbUtil.delete(DbVideoFile.class,  ConditionBuilder.getInstance().start().addCondition("url", df.getUrl()).end());
                DbUtil.delete(OkDlTask.class, ConditionBuilder.getInstance().start().addCondition("url", df.getUrl()).end());
            }else{
                File f = new File(df.getPath());
                if (!f.exists()){
                    DbUtil.delete(DbVideoFile.class,  ConditionBuilder.getInstance().start().addCondition("url", df.getUrl()).end());
                    DbUtil.delete(OkDlTask.class, ConditionBuilder.getInstance().start().addCondition("url", df.getUrl()).end());
                }else if (!TextUtils.isEmpty(df.getUrl()) && (df.getStatus() == DbVideoFile.Status.STATUS_DOWNLOADING) ){
                    // 重启下载
                    LogUtils.d(TAG,df.getUrl()+" "+df.getPath()+" "+df.getMd5()+" "+df.getStatus());
                    OkDlManager.getInstance().resumeTask(df.getUrl());
                }

            }
        }
        EventBus.getDefault().post(new EbPreDownload());
//        preDownload();
    }






}
